package com.minelx.woods.server.perspective;

import com.minelx.woods.server.entity.Users;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthenticatedControllerPerspective {

	private final Users users;

	public AuthenticatedControllerPerspective(Users users) {
		this.users = users;
	}

	@Around("execution(* com.minelx.woods.server.controller.*.*(..))")
	public Object decorate(ProceedingJoinPoint proceedingJoinPoint) {
		AuthenticatedProcessor procedure = new AuthenticatedProcessor(
				new JoinPointProcedure(proceedingJoinPoint),
				users,
				currentRequest().getHeader("token"));
		return procedure.proceed();
	}

	public static HttpServletRequest currentRequest() {
		RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
		assert attributes != null;
		return (HttpServletRequest) attributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
	}
}
